package com.adds.lvds.security.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.adds.lvds.core.trace.TraceContent;
import com.adds.lvds.core.trace.TraceService;
import com.adds.lvds.security.acegi.session.PmcPrincipal;
import com.adds.lvds.security.service.SysUserLogService;
import com.adds.lvds.security.service.SysUserService;

/**
 * 进行管理后台框架界面的类
 * 
 * @author zhangjian 2016-11-19
 * @Email:
 * @version 1.0v
 */
@Controller
@SuppressWarnings("all")
public class LogonController {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private AuthenticationManager myAuthenticationManager;

	@Inject
	private SysUserLogService sysUserLogService;
	@Inject
	private SessionRegistry sessionRegistry;

	/**
	 * @return
	 */
	@RequestMapping(value = "/login")
	public String login(Model model, HttpServletRequest request) {
		// 重新登录时销毁该用户的Session
		Object o = request.getSession().getAttribute(
				"ACEGI_SECURITY_LAST_USERNAME");
		if (null != o) {
			request.getSession()
					.removeAttribute("ACEGI_SECURITY_LAST_USERNAME");
		}
		return "/login";
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/sessionTimeout")
	public String sessionTimeout(Model model, HttpServletRequest request) {
		// 重新登录时销毁该用户的Session
		Object o = request.getSession().getAttribute(
				"ACEGI_SECURITY_LAST_USERNAME");
		if (null != o) {
			request.getSession()
					.removeAttribute("ACEGI_SECURITY_LAST_USERNAME");
		}
		return "/sessionTimeout";
	}

	/**
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index")
	public String index(Model model) {

		return "/index";
	}

	@RequestMapping(value = "/welcome")
	public String welcome(Model model) {
		return "/welcome";
	}
	@RequestMapping(value = "/403")
	public String error_403(Model model) {
		return "/403";
	}
	@RequestMapping(value = "/menu")
	public String menu(Model model) {
		return "/menu";
	}

	@RequestMapping(value = "/download")
	public void download(String fileName, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;

		String ctxPath = request.getSession().getServletContext()
				.getRealPath("/")
				+ "\\" + "filezip\\";
		String downLoadPath = ctxPath + fileName;
		System.out.println(downLoadPath);
		try {
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename="
					+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}



	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logoutPage(HttpServletRequest request,
			HttpServletResponse response) {
		Authentication auth = SecurityContextHolder.getContext()
				.getAuthentication();
		if (auth != null) {
			new SecurityContextLogoutHandler().logout(request, response, auth);
		}
		return "redirect:/login?logout";
								
	}

	@RequestMapping(value = "/offline")
	@ResponseBody
	public Map<String, Object> offline(String sessionId, String name,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<>();
		try {
			List<Object> userList = sessionRegistry.getAllPrincipals();
			for (int i = 0; i < userList.size(); i++) {
				PmcPrincipal userTemp = (PmcPrincipal) userList.get(i);
				if (userTemp.getUsername().equals(name)) {
					List<SessionInformation> sessionInformationList = sessionRegistry
							.getAllSessions(userTemp, false);
					if (sessionInformationList != null) {
						for (int j = 0; j < sessionInformationList.size(); j++) {
							sessionInformationList.get(j).expireNow();
							String remark = userTemp.getUsername() + "被管理员 踢下线";
							TraceService.info(TraceContent.SYSTEM, remark);
						}
					}
				}
			}
			map.put("errcode", "1");
			map.put("errmsg", "【" + name + "】被管理员 踢下线");
		} catch (Exception e) {
			map.put("errcode", "2");
			map.put("errmsg", "【" + name + "】被管理员 踢下线数据异常");
		}
		return map;
	}
}
